package com.lz.comm.image.progress

import com.bumptech.glide.Priority
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.data.DataFetcher
import okhttp3.Call
import okhttp3.Response
import java.io.IOException
import java.io.InputStream

class ProgressOkHttpStreamFetcher(
    private val url: ProgressGlideUrl,
    private val client: Call.Factory
) : DataFetcher<InputStream>, okhttp3.Callback {
    private var responseBody: ProgressResponseBody? = null
    private var stream: InputStream? = null
    private var callback: DataFetcher.DataCallback<in InputStream?>? = null
    @Volatile
    private var call: Call? = null

    override fun loadData(priority: Priority, callback: DataFetcher.DataCallback<in InputStream>) {
        TODO("Not yet implemented")
    }

    override fun onFailure(call: Call, e: IOException) {
        callback?.onLoadFailed(e)
    }

    override fun onResponse(call: Call, response: Response) {
        response.request().url()
    }

    override fun cleanup() {
        try {
            stream?.close()
        } catch (_: IOException) {
        }
        responseBody?.close()
        callback = null
    }

    override fun cancel() {
        val local = call
        local?.cancel()
    }

    override fun getDataClass(): Class<InputStream> = InputStream::class.java

    override fun getDataSource(): DataSource = DataSource.REMOTE
}